package ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import ejb.entity.Position;
import ejb.entity.User;

@Stateless
public class DefaultPositionDAO implements PositionDAO {

	@PersistenceContext
	EntityManager em;
	
	@Override
	public Position create(Position position) {
		try{
			em.persist(position);
		}catch(IllegalArgumentException e){
			return null;
		}
		return position;
	}
	
	@Override
	public Position findById(int id) {
		try{
			Position n = (Position)em
					.createNamedQuery("DefaultPosition.findById")
					.setParameter("id", id)
					.getSingleResult();
			return n;
		}catch(NoResultException nre){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
		
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<Position> findByUser(User user) {
		List<Position> n = new ArrayList<Position>();
		n = ((List<Position>)em
				.createNamedQuery("DefaultPosition.findByUser")
				.setParameter("user", user)
				.getResultList());
		return n;
	}

	@Override
	public Position findByName(String name) {
		try{
			Position p = (Position)em
					.createNamedQuery("DefaultPosition.findByName")
					.setParameter("name", name)
					.getSingleResult();
			return p;
		}catch(NoResultException n){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
	}	
	
	
	@Override
	public Position findByNameAndUser(String name, User user) {
		try{
			Position p = (Position)em
					.createNamedQuery("DefaultPosition.findByNameAndUser")
					.setParameter("name", name).setParameter("user", user)
					.getSingleResult();
			return p;
		}catch(NoResultException n){
			return null;
		}catch(IllegalArgumentException e){
			return null;
		}
	}	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Position> findByUserAndForecast(User user, boolean forecast) {
		List<Position> n = new ArrayList<Position>();
		n = ((List<Position>)em
				.createNamedQuery("DefaultPosition.findByUserAndForecast")
				.setParameter("user", user).setParameter("forecast", forecast)
				.getResultList());
		return n;
	}	
	
	@Override
	public boolean delete(Position Position) {
		try{
			em.remove(Position);
		}catch(IllegalArgumentException e){
			return false;
		}
		return true;
	}
	
}
